package com.olddriver.crm.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.olddriver.crm.domain.Employee;
import com.olddriver.crm.domain.Systemlog;
import com.olddriver.crm.service.ISystemlogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

public class SystemLogUtil {

    @Autowired
    private ISystemlogService systemlogService;

    public void writeLog(JoinPoint joinPoint) throws JsonProcessingException {
        if (joinPoint.getTarget() instanceof ISystemlogService){
            return;
        }
        Systemlog systemlog = new Systemlog();
        systemlog.setOptime(new Date());
        systemlog.setFunction(joinPoint.getSignature().toString());
        systemlog.setOpuser((Employee) SecurityUtils.getSubject().getPrincipal());
        systemlog.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        systemlog.setOpip(requestAttributes.getRequest().getRemoteAddr());

        systemlogService.insert(systemlog);
    }
}
